<template>
  <div>
    <h2>上传功能</h2>
    <UpdateEmployees :on-success="handldSuccess" />
  </div>
</template>

<script>
import { UpdataUSerInfoAPI } from '@/api/emploees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    handldSuccess({ results }) {
      if (this.type === 'user') {
        this.addUpdate(results)
      }
    },
    async addUpdate(results) {
      const list = this.formatEmploees(results)
      await UpdataUSerInfoAPI(list)
      this.$message.success('上传成功')
      this.$router.back()
    },
    formatEmploees(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const list = []
      results.forEach(item => {
        const obj = {}
        Object.keys(item).forEach(key => {
          const englishList = userRelations[key]
          if (['timeOfEntry', 'correctionTime'].includes(englishList)) {
            obj[englishList] = this.formatExcelDate(item[key])
          } else {
            obj[englishList] = item[key]
          }
        })
        list.push(obj)
      })
      return list
    },
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
